<template>
  <el-drawer title="建议内容" size="600px" :with-header="false" :visible.sync="drawer">
    <div class="advice-box">
      <div class="advice-add">
        <div class="advice-title">报告上传</div>
        <el-form ref="ruleForm" :model="form" :rules="rules" label-position="right" label-width="80px">
          <el-form-item label="项目名称" prop="projectIdList">
            <div class="project-select" @click="selectProject">
              <span>请选择项目名称</span>
            </div>
            <div v-if="form.projectIdList.length > 0">
              <ul class="project-box">
                <li class="s-box" v-for="(item, index) in form.projectIdList" :key="index">{{item.name}}
                  <span>{{'('+item.value+')'}}</span>
                  <i class="el-icon-circle-close" @click="removeProject(index)"></i>
                </li>
              </ul>
            </div>
          </el-form-item>
          <el-form-item label="所属月份" prop="month">
            <el-date-picker v-model="form.month" format="yyyy-MM" value-format="yyyyMM" type="month" placeholder="所属月份" :picker-options="pickerOptions"  />
          </el-form-item>
          <el-form-item label="选择文件" prop="fileName">
            <div class="file-class">
              <el-upload
                ref="fileUpload"
                class="upload-demo"
                action="#"
                :limit="1"
                accept=".xls,.xlsx,.doc,.docx,.pdf,.ppt"
                :multiple="false"
                :auto-upload="false"
                :show-file-list="false"
                :before-upload="beforeFileUpload"
                :http-request="uploadHttpRequest"
                :on-change="handleChange">
                <el-button class="project-select1">
                  <span v-if="form.fileName" style="color: #606266;">{{ form.fileName }}</span>
                  <span v-else>请选择文件</span>
                </el-button>
              </el-upload>
              <div class="file-delete" @click="deleteFile"><i class="el-icon-delete"></i></div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="advice-submit">
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </div>
    <ProjectConfigModal ref="projectConfigRef" @update="changeProject" />
  </el-drawer>
</template>
<script>
import { Base64 } from 'js-base64'
import crypto from 'crypto-js'
import axios from 'axios';
import {ossOssPrivateSign} from '@/api/singleraView/teskReport'
import { commonOssFileUrl, uploadProject, getOssConfig } from '@/api/singleraView/teskReport/taskReport'
import ProjectConfigModal from '@/views/singleraView/taskReport/projectConfigModal.vue'
export default {
  data() {
    return {
      drawer: false,
      configUrl: '',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      projectList: [],
      form: {
        content: '',
        month: '',
        projectIdList: [],
        reportType: 'output',  //销项报告
        fileName: '',
      },
      messageType: 'add',
      rules: {
        projectIdList: [
          { type: 'array', required: true, message: '请选择项目', trigger: 'blur' },
        ],
        month: [
          { required: true, message: '所属月份', trigger: 'blur' }
        ],
        fileName: [
          { required: true, message: '请选择文件', trigger: 'blur' }
        ],
      },
      pickerOptions: {
        disabledDate(time){
          const now = new Date();
          const year = now.getFullYear();
          const month = now.getMonth();
          const day = now.getDate();
          const twelveMonthsAgo = new Date(year, month - 12, day);
          const lastMonth = new Date(year, month + 6, day);
          return time.getTime() < twelveMonthsAgo || time.getTime() > lastMonth;
        }
      }
    }
  },
  components: {
    ProjectConfigModal
  },
  methods: {
    init(){
      this.drawer = true
      // this.form.fileName = ''
    },
    cancel() {
      this.form.month = ''
      this.form.fileName = ''
      this.form.projectIdList = []
      this.$refs.fileUpload.clearFiles()
      this.drawer = false
    },
    deleteFile(){
      console.log("deleteFile")
      this.form.fileName = ''
      this.$refs.fileUpload.clearFiles()
    },
    selectProject(){
      this.$refs.projectConfigRef.getInit()
    },
    removeProject(index){
      this.form.projectIdList.splice(index, 1)
    },
    changeProject(multi){
      this.form.projectIdList = multi
    },
    handleChange(file){
      this.form.fileName = file.name
    },
    exceedChange(file){
      this.form.fileName = file[0].name
    },
    beforeFileUpload(file){
      //   文件类型限制
      const isAllowed = /^.ppt|.doc|.docx|.xls|.xlsx|.pdf$/.test(
        file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      )
      if (!isAllowed) {
        this.$message.error('只能上传PPT、PDF、Word、Excel文件！');
        return false;
      }
    },
    uploadHttpRequest(file){
      this.fileUpload(file)
    },
    async fileUpload(file){
      console.log(file)
      let ranDomName = Math.random().toString(36).substring(2) // 11位随机数
      let filePath = `property/${file.file.name.split('.').pop()}/`
      let tempName = ranDomName + '.' + file.file.name.split('.').pop()
      const ossConfig = await this.getOSSConfig()
      const key = `${filePath}${this.form.fileName}`
      const OSS_HOST = `https://${ossConfig.bucket}.${ossConfig.endPoint}`;
      let formData = new FormData();
      formData.append('key', key);
      formData.append('success_action_status', '200');
      formData.append('OSSAccessKeyId', ossConfig.OSSAccessKeyId)
      formData.append('accessKeySecret', ossConfig.accessKeySecret)
      formData.append('bucket', ossConfig.bucket)
      formData.append('endPoint', ossConfig.endPoint)
      formData.append('signature', ossConfig.signature)
      formData.append('policy', ossConfig.policy)
      formData.append('securityToken', ossConfig.securityToken)
      formData.append('x-oss-security-token', ossConfig.securityToken)
      formData.append('file', file.file)
      const result = await axios({
        url: OSS_HOST,
        method: 'post',
        name: 'file',
        data: formData,
      })

      try {
          const pUpload = {
            file: {
              fileName: this.form.fileName,
              path: key
            },
            month: this.form.month,
            projectIdList: this.form.projectIdList.map(p => { return p.value }),
            reportType: "output"
          }
          // console.log(pUpload)
          uploadProject(pUpload).then(() => {
            this.form.month = ''
            this.form.fileName = ''
            this.form.projectIdList = []
            this.$refs.fileUpload.clearFiles()
            this.$message.success("销项报告上传成功")
            this.drawer = false
            this.$emit('update')
          })
      } catch (error){
        console.log(error)
      }
    },
    async getOSSConfig() {
      const rsp = await getOssConfig();
      const policyText = {
        expiration: rsp.expiration, // 设置policy过期时间。
        conditions: [
          // 限制上传大小。
          ["content-length-range", 0, 1024 * 1024 * 1024],
        ],
      };
      const policy = Base64.encode(JSON.stringify(policyText))
      const sha1 = crypto.HmacSHA1(policy, rsp.accessKeySecret);
      const signature = crypto.enc.Base64.stringify(sha1);
      return {
        policy,
        signature,
        expiration: rsp.expiration,
        regionId: rsp.regionId,
        requestId: rsp.requestId,
        OSSAccessKeyId: rsp.accessKeyId,
        accessKeySecret: rsp.accessKeySecret,
        bucket: rsp.bucket,
        endPoint: rsp.endPoint,
        securityToken: rsp.securityToken,
        'x-oss-security-token': rsp.securityToken
      }
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$refs.fileUpload.submit()
          this.drawer = false
          // this.form.month = ''
          // this.form.fileName = ''
          // this.form.projectIdList = []
        } else {
          this.$message.error('请完善表单相关信息！');
          return false;
        }
      });
    }
  }
}
</script>
<style scoped lang="scss">
.advice-box{
  position: relative;
  padding: 20px;
  height: 100%;
  overflow: auto;
  .advice-title{
    font-weight: bold;
    font-size: 18px;
    margin: 20px 0 15px 0;
  }
  .advice-option{
    padding: 10px 0;
    font-size: 15px;
    display: flex;
    flex-direction: row;
    .content{
      flex: 1;
    }
    .left{
      width: 80px;
    }
  }
  .history-box{
    margin-top: 5px;
    display: flex;
    flex-direction: row;
    align-items: center;
    border: 1px solid #bfbfbf;
    padding: 10px;
    border-radius: 5px;
    background: #bfbfbf;
  }
  .advice-submit{
    margin: 20px 0;
    text-align: center;
  }
}

.project-select{
  width: 100%;
  height: 34px;
  background: #FFFFFF;
  border-radius: 5px;
  color: #C0C4CC;
  padding: 0 10px;
  cursor: pointer;
  border: 1px solid #DCDFE6;
  position: relative;
  overflow: hidden;
  .icon{
    position: absolute;
    right: 5px;
    top: 0;
  }
}
.file-class{
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  .project-select1{
    width: 450px;
    height: 34px;
    background: #FFFFFF;
    border-radius: 5px;
    color: #C0C4CC;
    padding: 0 10px;
    cursor: pointer;
    border: 1px solid #DCDFE6;
    position: relative;
    overflow: hidden;
    // .icon{
    //   position: absolute;
    //   right: 5px;
    //   top: 0;
    // }
  }
  .file-delete{
    
  }
}

.project-box{
  marign: 0;
  padding: 0;
  list-style: none;
  .s-box{
    position: relative;
    float: left;
    display: block;
    margin-right: 5px;
    margin-bottom: 5px;
    padding: 0 30px 0 10px;
    border: 1px solid #DCDFE6;
    border-radius: 5px;
    .el-icon-circle-close{
      position: absolute;
      right: 5px;
      top: 11px;
      cursor: pointer;
      font-size: 16px;
    }
  }
}
::v-deep .el-date-editor.el-input{
  width: 100%;
}
::v-deep .el-upload{
  width: 100%;
}
::v-deep .el-button{
  text-align: left;
}
</style>
